var express = require('express');
var router = express.Router();
var BaseData = require('./config/db');
db = new BaseData();
db.connection.connect();

/* GET home page. */
router.get('/', function(req, res, next) {
	if(req.session.token) {
		res.redirect('/');
	} else {
		res.render('register', {
			title: 'Express'
		});
	}
});

router.get('/auth/', function(req, res, next) {
	if(req.session.token) {
		res.redirect('/');
	} else {
		res.redirect('/register');
	}
})

router.post('/auth/', function(req, res, next) {
	var uPattern = /^[a-zA-Z0-9_-]{4,16}$/,
		ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,5})$/;

	function getClientIp(req) {
		return req.headers['x-forwarded-for'] ||
			req.connection.remoteAddress ||
			req.socket.remoteAddress ||
			req.connection.socket.remoteAddress;
	};
	var WoUser = req.body.WoUser,
		WoPass = req.body.WoPass,
		WoPass2 = req.body.WoPass2,
		WoMail = req.body.WoMail,
		agreement = req.body.agreement,
		msg = "";
	if(!uPattern.test(WoUser)) {
		msg = "用户名长度4-16位";
	}
	if(WoPass.length < 6) {
		msg = "密码最少6位"
	}
	if(WoPass != WoPass2) {
		msg = "两次密码不一致"
	}
	if(!ePattern.test(WoMail)) {
		msg = "邮箱格式不正确"
	}
	if(agreement != "true") {
		msg = "未阅读用户协议和隐私条款"
	}
	if(msg) {
		res.json({
			"code": "3001",
			"msg": msg
		})
		return false;
	}
	db.connection.query('SELECT count(*) FROM `userinfo` WHERE User = ?', [WoUser], function(err, rows) {
		if(err) {
			res.json({
				"code": "3002",
				"msg": "系统出现错误,请联系管理员"
			})
			return false;
		} else {
			if(rows[0]['count(*)'] > 0) {
				res.json({
					"code": "3001",
					"msg": "帐号“" + WoUser + "”已存在,请换其他帐号"
				})
				return false;
			}
			db.connection.query('SELECT count(*) FROM `userinfo` WHERE ?', ['1'], function(err, rows) {
				req.session.token = null;
				var time = String((new Date()).valueOf());
				WoPass = db.Toolmd5(WoPass);
				var User_id = "p" + time.substring(3, time.length) + (parseInt(rows[0]['count(*)']) + 1)
				db.connection.query('INSERT INTO `userinfo`(`User_id`, `User`, `PassWord`, `Name`, `Email`, `RegTime`, `RegIp`, `LogIp`) VALUES (?,?,?,?,?,?,?,?)', [User_id, WoUser, WoPass, '神秘人p' + time.substring(3, time.length), WoMail, new Date().toLocaleString(), getClientIp(req), getClientIp(req)],
					function(err, rows) {
						if(err) {
							res.json({
								"code": "3002",
								"msg": "注册出现错误,请联系管理员"
							})
						} else {
							if(rows) {
								req.session.token = db.Toolaes(User_id, "encryption") + "_" + redomToken();
								res.json();
							}
						}
					})
			});
		}
	})

	function redomToken() {
		var len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		var maxpos = chars.length;
		var str = '';

		for(var i = 0; i < len; i++) {
			str += chars.charAt(Math.floor(Math.random() * maxpos))
		}

		return str;
	}

})

module.exports = router;